import { useRequest, useSetState } from 'ahooks'
import { Modal, Badge, Divider, Select, InputNumber, Input, Switch, message, TreeSelect } from 'antd'
import { useEffect } from 'react'
import { useState } from 'react'
import GridLayout from 'react-grid-layout'
import uuid from 'react-uuid'
import {
    WeChatImageUrl,
    WeChatMenuListArr,
    WeChatMenuStyleList,
    WeChatMenuSmallTitleList,
    SmallTitle001,
    SmallTitle002,
} from './WeChatCommon'

import { OptionsSelect, ModuleTitle001, WeChatModule, WeChatModuleExtra } from './WeChatModule'
import { colorCount } from './Common'
import { Http } from '../Api'

const { Ribbon } = Badge

export const SetUpCommonModal = ({ title, Off, SetUpCommonModalEvent, data }) => {
    return (
        <Modal
            className="ModalTitle SetUpCommonModal"
            open={true}
            footer={null}
            maskClosable={false}
            onCancel={Off}
            destroyOnClose
            title={title}
            centered
            width={'60vw'}
        >
            {(() => {
                const dataList = {
                    ImageSelect,
                    MenuSetup,
                    MenuItemTabsOptions,
                    MenuItemTabsDispose,
                }
                const Template = dataList[data.type]
                return <Template SetUpCommonModalEvent={SetUpCommonModalEvent} data={data} Off={Off} />
            })()}
        </Modal>
    )
}

export const ImageSelect = ({ SetUpCommonModalEvent, data }) => {
    const { theme, list, active, url, key } = data
    const [Active, setActive] = useState(active)
    return (
        <div className="ImageSelect">
            {Object.keys(list).map((item, index) =>
                Active === item ? (
                    <Ribbon key={index} text="当前" color={theme}>
                        <img src={url + list[item]} alt="" />
                    </Ribbon>
                ) : (
                    <div
                        key={index}
                        onClick={() => {
                            setActive(item)
                            SetUpCommonModalEvent.emit({ [key]: item })
                        }}
                    >
                        <img src={url + list[item]} alt="" />
                    </div>
                ),
            )}
        </div>
    )
}

export const MenuSetup = ({ SetUpCommonModalEvent, data, Off }) => {
    console.log(SetUpCommonModalEvent, data)

    const [layout, setLayout] = useState([])
    const [Uuid, setUuid] = useState()
    const [DeleteArr, setDeleteArr] = useState([])
    const [MenuData, setMenuData] = useSetState({
        menuStyle: 'MenuStyle001',
        menuSortId: 0,
        smallStatus: true,
        smallTheme: true,
        smallStyle: 'SmallTitle001',
        smallName: '小标题名称',
        smallEnglish: '',
        smallOptions: {},
    })

    useEffect(() => {
        let deleteArr = [
            'd9b18d92-2f3d-41c8-a82a-0777bb90be80',
            '51425806-a4de-48fb-8a03-02b54745ea35',
            '8d4cc65c-3695-47e6-84a7-50f3349bafca',
        ]

        const { MenuList, index } = data
        MenuList.forEach(({ menuArr }) => menuArr.forEach(({ i }) => (deleteArr = [...deleteArr, i])))

        if (index || index === 0) {
            const {
                menuStyle,
                menuSortId,
                smallStatus,
                smallTheme,
                smallStyle,
                smallName,
                smallEnglish,
                smallOptions,
                menuArr,
            } = MenuList[index]

            setMenuData({
                menuStyle,
                menuSortId,
                smallStatus,
                smallTheme,
                smallStyle,
                smallName,
                smallEnglish,
                smallOptions,
            })
            menuArr.forEach(({ i }) => (deleteArr = deleteArr.filter(e => e !== i)))
            setLayout(menuArr)
        }
        setDeleteArr(deleteArr)
    }, [data, setMenuData])

    const DeleteMenu = uuid => {
        let data = JSON.parse(JSON.stringify(layout))
        data.splice(
            data.findIndex(v => v.i === uuid),
            1,
        )
        setLayout(data)
    }

    return (
        <div className="MenuSetUpModal">
            <div className="preview">
                {(() => {
                    const SmallTitleList = {
                        SmallTitle001,
                        SmallTitle002,
                    }
                    const Template = SmallTitleList[MenuData.smallStyle]
                    return (
                        <>
                            {MenuData.smallStatus && (
                                <Template
                                    title={MenuData.smallName}
                                    english={MenuData.smallEnglish}
                                    status={MenuData.smallTheme}
                                    theme={data.theme}
                                    // options={MenuData.smallOptions}
                                />
                            )}
                            <GridLayout
                                className="GridLayout"
                                layout={layout}
                                margin={[10, 10]}
                                cols={3}
                                rowHeight={160}
                                width={500}
                                isDroppable={true}
                                isResizable={false}
                                onDrop={e => {
                                    let NewBox = e.findIndex(v => v.i === '__dropping-elem__')
                                    e[NewBox] = { ...e[NewBox], i: Uuid }
                                    setLayout(e)
                                    setUuid()
                                }}
                                onResizeStop={e => setLayout(e)}
                                onDragStop={e => setLayout(e)}
                            >
                                {layout.map(({ i }) => (
                                    <div className={MenuData.menuStyle + 'Item'} key={i}>
                                        <div className="GridLayoutDelete">
                                            <div
                                                style={{ '--color': '#eb261a', '--hsl': colorCount('#eb261a') + '%' }}
                                                onClick={() => DeleteMenu(i)}
                                            >
                                                <span></span>
                                                <span></span>
                                                <span></span>
                                                <span></span>
                                                删除
                                            </div>
                                        </div>
                                        <img src={WeChatImageUrl + MenuData.menuStyle + '/' + i + '.png'} alt="" />
                                        <div className="Title">
                                            <div>{WeChatMenuListArr.find(v => v.uuid === i).tableName}</div>
                                            <div>{WeChatMenuListArr.find(v => v.uuid === i).english}</div>
                                        </div>
                                    </div>
                                ))}
                            </GridLayout>
                        </>
                    )
                })()}
            </div>
            <div className="SetUp">
                <div>
                    <Divider orientation="left" orientationMargin="0">
                        菜单基础设置
                    </Divider>
                    <div className="InputLabel">
                        <div>菜单样式 : </div>
                        <Select
                            value={MenuData.menuStyle}
                            options={WeChatMenuStyleList}
                            onChange={e => setMenuData({ menuStyle: e })}
                        />
                    </div>
                    <div className="InputLabel">
                        <div>菜单排序 : </div>
                        <InputNumber
                            min={0}
                            value={MenuData.menuSortId}
                            placeholder="请输入排序字段"
                            onChange={e => setMenuData({ menuSortId: e ?? 0 })}
                        />
                    </div>
                </div>
                <div>
                    <Divider orientation="left" orientationMargin="0">
                        小标题设置
                    </Divider>
                    <div className="InputLabel">
                        <div>小标题状态 : </div>
                        <Switch
                            checkedChildren="开启"
                            unCheckedChildren="关闭"
                            checked={MenuData.smallStatus}
                            onChange={e => setMenuData({ smallStatus: e })}
                        />
                    </div>
                    <div className="InputLabel">
                        <div>小标题主题 : </div>
                        <Switch
                            checkedChildren="开启"
                            unCheckedChildren="关闭"
                            checked={MenuData.smallTheme}
                            onChange={e => setMenuData({ smallTheme: e })}
                        />
                    </div>
                    <div className="InputLabel">
                        <div>小标题样式 : </div>
                        <Select
                            value={MenuData.smallStyle}
                            options={WeChatMenuSmallTitleList}
                            onChange={e => setMenuData({ smallStyle: e })}
                        />
                    </div>
                    <div className="InputLabel">
                        <div>小标题名称 : </div>
                        <Input
                            value={MenuData.smallName}
                            placeholder="请输入小标题名称"
                            onChange={e => setMenuData({ smallName: e.target.value })}
                        />
                    </div>
                    <div className="InputLabel">
                        <div>小标题English : </div>
                        <Input
                            value={MenuData.smallEnglish}
                            placeholder="请输入小标题English"
                            onChange={e => setMenuData({ smallEnglish: e.target.value })}
                        />
                    </div>
                    <div className="InputLabel">
                        <div>小标题操作 : </div>
                        <div>操作设置</div>
                    </div>
                </div>
                <div>
                    <Divider orientation="left" orientationMargin="0">
                        可选菜单列表
                    </Divider>
                    <div className="Optional">
                        {WeChatMenuListArr.map(({ uuid, tableName, english }) => {
                            if (
                                layout.findIndex(v => v.i === uuid) === -1 &&
                                DeleteArr.findIndex(v => v === uuid) === -1
                            )
                                return (
                                    <div
                                        className={MenuData.menuStyle + 'Item'}
                                        key={uuid}
                                        draggable={true}
                                        onDragStart={() => setUuid(uuid)}
                                        style={{ margin: 8 }}
                                    >
                                        <img src={WeChatImageUrl + MenuData.menuStyle + '/' + uuid + '.png'} alt="" />
                                        <div className="Title">
                                            <div>{tableName}</div>
                                            <div>{english}</div>
                                        </div>
                                    </div>
                                )
                            else return false
                        })}
                    </div>
                </div>
            </div>
            <div className="Submit">
                <div
                    style={{ background: data.theme, '--hsl': colorCount(data.theme) + '%' }}
                    onClick={() => {
                        const { index, MenuList } = data
                        if (index || index === 0) {
                            let arr = MenuList
                            arr[index] = { ...MenuData, menuArr: layout }
                            arr.sort((a, b) => a.menuSortId - b.menuSortId)
                            SetUpCommonModalEvent.emit(arr)
                            message.success('成功新增菜单')
                            Off()
                        } else {
                            let arr = [...MenuList, { ...MenuData, menuArr: layout }]
                            arr.sort((a, b) => a.menuSortId - b.menuSortId)
                            SetUpCommonModalEvent.emit(arr)
                            message.success('成功修改菜单')
                            Off()
                        }
                    }}
                >
                    保存菜单
                </div>
            </div>
        </div>
    )
}

export const MenuItemTabsOptions = ({ SetUpCommonModalEvent, data, Off }) => {
    const [TABSName, setTABSName] = useState()
    const [TABSSort, setTABSSort] = useState()

    const SubmitTabs = () => {
        if (!TABSName || !TABSSort) {
            message.info('请补全信息')
            return false
        }
        if (data.uuid) {
            const { list, uuid } = data
            list.find(v => v.uuid === uuid).title = TABSName
            list.find(v => v.uuid === uuid).sortId = TABSSort
            list.sort((a, b) => a.sortId - b.sortId)
            SetUpCommonModalEvent.emit({ list })
        } else {
            const UUID = uuid()
            const newData = [...data.list, { uuid: UUID, sortId: TABSSort, title: TABSName }]
            newData.sort((a, b) => a.sortId - b.sortId)
            SetUpCommonModalEvent.emit({
                list: newData,
                newUuid: UUID,
            })
            Off()
        }
        Off()
    }

    useEffect(() => {
        if (data.uuid) {
            const { list, uuid } = data
            const tabs = list.find(v => v.uuid === uuid)
            setTABSName(tabs.title)
            setTABSSort(tabs.sortId)
        }
    }, [data])

    return (
        <div className="MenuItemTabsOptions">
            <div>
                <div>TABS名称</div>
                <Input placeholder="请输入TABS的名称" value={TABSName} onChange={e => setTABSName(e.target.value)} />
            </div>
            <div>
                <div>TABS排序</div>
                <InputNumber min={1} placeholder="请输入TABS的排序" value={TABSSort} onChange={e => setTABSSort(e)} />
            </div>
            <div className="Submit">
                <div style={{ background: data.theme }} onClick={SubmitTabs}>
                    保存设置
                </div>
            </div>
        </div>
    )
}

export const MenuItemTabsDispose = ({ SetUpCommonModalEvent, data, Off }) => {
    const { active, theme, disPose, module } = data
    const [title, uuid] = module.split('_')
    const Template = WeChatModule[title]
    const [DisPoseData, setDisPoseData] = useSetState(disPose)
    const SubmitModule = () => SetUpCommonModalEvent.emit({ active, uuid, DisPoseData })
    const [ApiData, setApiData] = useState([])
    const { runAsync: getTree } = useRequest(Http, { manual: true, onSuccess: res => setApiData(res) })

    useEffect(() => {
        if (disPose.api) getTree({ url: disPose.api })
    }, [disPose, getTree])

    return (
        <div className="MenuItemTabsDispose">
            <div>
                <ModuleTitle001 data={DisPoseData} back={theme} />
                <Template ModuleItemEvent={false} data={DisPoseData} />
            </div>
            <div>
                <div>
                    <Divider orientation="left" orientationMargin="0">
                        头部菜单设置
                    </Divider>
                    <div className="DisposeOptions">
                        <div>菜单状态</div>
                        <Switch
                            checkedChildren="开启"
                            unCheckedChildren="关闭"
                            checked={DisPoseData.status}
                            onChange={e => setDisPoseData({ status: e })}
                        />
                    </div>
                    <div className="DisposeOptions">
                        <div>菜单标题</div>
                        <Input
                            placeholder="请输入菜单标题"
                            value={DisPoseData.title}
                            onChange={e => setDisPoseData({ title: e.target.value })}
                        />
                    </div>
                    <div className="DisposeOptions">
                        <div>菜单副标题</div>
                        <Input
                            placeholder="请输入菜单副标题"
                            value={DisPoseData.smallTitle}
                            onChange={e => setDisPoseData({ smallTitle: e.target.value })}
                        />
                    </div>
                    <div className="DisposeOptions">
                        <div>菜单主题</div>
                        <Switch
                            checkedChildren="开启"
                            unCheckedChildren="关闭"
                            checked={DisPoseData.theme}
                            onChange={e => setDisPoseData({ theme: e })}
                        />
                    </div>
                    <div className="DisposeOptions">
                        <div>操作状态</div>
                        <Switch
                            checkedChildren="开启"
                            unCheckedChildren="关闭"
                            checked={DisPoseData.option}
                            onChange={e => setDisPoseData({ option: e })}
                        />
                    </div>

                    {DisPoseData.option && (
                        <div className="DisposeOptions">
                            <div>操作状态</div>
                            <Select
                                value={DisPoseData.options}
                                options={OptionsSelect}
                                onChange={e => setDisPoseData({ options: e })}
                            />
                        </div>
                    )}

                    {WeChatModuleExtra[title] && (
                        <>
                            <Divider orientation="left" orientationMargin="0">
                                {WeChatModuleExtra[title].label}
                            </Divider>
                            {WeChatModuleExtra[title].children.map(({ uuid, label, value, type, options }) => (
                                <div className="DisposeOptions" key={uuid}>
                                    <div>{label}</div>
                                    {(() => {
                                        switch (type) {
                                            case 'select':
                                                return (
                                                    <Select
                                                        value={DisPoseData[value]}
                                                        options={options}
                                                        onChange={e => setDisPoseData({ [value]: e })}
                                                    />
                                                )
                                            case 'selectMultiple':
                                                return (
                                                    <Select
                                                        mode="multiple"
                                                        value={DisPoseData[value]}
                                                        options={options}
                                                        onChange={e => setDisPoseData({ [value]: e })}
                                                    />
                                                )
                                            case 'input':
                                                return (
                                                    <Input
                                                        value={DisPoseData[value]}
                                                        onChange={e => setDisPoseData({ [value]: e.target.value })}
                                                    />
                                                )
                                            case 'switch':
                                                return (
                                                    <Switch
                                                        checkedChildren="开启"
                                                        unCheckedChildren="关闭"
                                                        checked={DisPoseData[value]}
                                                        onChange={e => setDisPoseData({ [value]: e })}
                                                    />
                                                )
                                            case 'treeSelect':
                                                return (
                                                    <TreeSelect
                                                        showSearch
                                                        style={{ width: '100%' }}
                                                        value={DisPoseData[value]}
                                                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                                        placeholder="请选择文件柜节点"
                                                        fieldNames={{ label: 'tableName', value: 'uuid' }}
                                                        treeDefaultExpandAll
                                                        onChange={e => setDisPoseData({ [value]: e })}
                                                        treeData={ApiData}
                                                    />
                                                )
                                            default:
                                                break
                                        }
                                    })()}
                                </div>
                            ))}
                        </>
                    )}
                </div>
                <div>
                    <div style={{ background: theme }} onClick={SubmitModule}>
                        保存
                    </div>
                </div>
            </div>
        </div>
    )
}
